package com.mirror.tk.api.common.support;

import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.jose4j.jwt.JwtClaims;
import org.jose4j.jwt.MalformedClaimException;
import org.jose4j.lang.JoseException;

import com.mirror.tk.api.utils.JwtUtil;

/**
 * Title:JWT门面类
 */
public class JwtFace {

	public static Map<String, JwtUser> userMap = new HashMap<String, JwtUser>();
	
	public static final String CLAIMS_KEY = "claims";
	
	/**
	 * 获取jwt认证信息
	 * @param request
	 * @return
	 */
	public static JwtClaims getClaims(HttpServletRequest request){
		return (JwtClaims) request.getAttribute(CLAIMS_KEY);
	}
	
    /**
     * 获取 jwt Id
     * @param request
     * @return String
     */
    public static String getJwtId(HttpServletRequest request){
        try {
			return getClaims(request).getJwtId();
		} catch (MalformedClaimException e) {
			e.printStackTrace();
		}
        return null;
    }
    
	/**
	 * 生成jwt并存入缓存
	 * @param user
	 * @return
	 */
	public static String setJwtUser(JwtUser user) {
		try {
			userMap.put(user.getPhone(), user);
			return JwtUtil.createJwt(user);
		} catch (JoseException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	/**
	 * 重新生成jwt
	 */
	public static String updateJwtUser(JwtUser user) {
		return setJwtUser(user);
	}

    /**
     * 获取当前会话用户
     * @param request
     * @return
     */
    public static JwtUser getJwtUser(HttpServletRequest request){
        return (JwtUser) request.getAttribute(JwtUser.JWT_USER_OBJECT_KEY);
    }
    
    /**
     * 获取当前会话用户是否登录
     * @param request
     * @return
     */
    public static Boolean isUserLogin(HttpServletRequest request){
        return getJwtUser(request) != null;
    }
    
    /**
     * 获取在线的用户
     * @param tel - 电话号码
     * @return
     */
    public static JwtUser getOnlineJwtUser(String tel){
        return userMap.get(tel);
    }

    /**
     * 退出登录
     * @param request
     * @return
     */
	public static Boolean logout(HttpServletRequest request) {
		if(isUserLogin(request)){
			userMap.remove(getJwtUser(request).getPhone());
		}
		return true;
	}
	
}
